<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

class Authorization
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        if (!app()->environment('local')) {
            $datetime = $request->input('datetime');
            $now = Carbon::now();
            if (empty($datetime) || $now->subMinutes(5)->gt($datetime) || $now->addMinutes(10)->lt($datetime)) {
                throw_invalid_request_exception('secret-key-invalid', ['reason' => 'datetime must Within ten minutes']);
            }
            $secret_key = $request->input('secret_key');
            if (empty($secret_key)) {
                throw_invalid_request_exception('secret-key-invalid', ['reason' => 'secret_key required']);
            }
            $data = $request->all();
            if(isset($data['s'])){
                unset($data['s']);
            }
            unset($data['secret_key']);
            $data['secret_key'] = config('app.secret_key');
            ksort($data);
            $json = json_encode($data);
            $key_current = md5($json);
            if (strcmp($secret_key, $key_current) != 0) {
                if (config('app.self_debug')) {
                    throw_invalid_request_exception('secret-key-invalid', ['reason' => 'secret_key vaild', 'json' => $json, 'key_current' => $key_current]);
                } else {
                    throw_invalid_request_exception('secret-key-invalid');
                }
            }
        }
        return $next($request);
    }
}
